<template>
  <el-dialog
    title="添加项目"
    :visible.sync="dialogVisible"
    width="500px">
    <el-form ref="form" :model="form" :rules="rules" label-width="60px" v-loading="articleListLoading">
      <el-form-item label="项目" prop="articleId">
        <el-select v-model="form.articleId" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in articleList" :label="item.name" :value="item._id" :key="item._id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogVisible = false">取 消</el-button>
      <el-button size="small" :loading="loading" type="primary" @click="okClick">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts">
  import { Component, Vue } from 'vue-property-decorator'
  import { Form } from 'element-ui'
  import WPopView from '@/utils/popView'
  import ArticleModel from '@/models/ArticleModel'
  import AccountModel from '@/models/AccountModel'

  @Component({
    name: 'AddArticle',
  })
  export default class ChangePassword extends Vue{

    private dialogVisible = false

    private loading = false
    private articleListLoading = false
    private articleList: Array<ArticleModel> = []
    private accountModel!: AccountModel

    // 项目数组

    form = {
      articleId: ''
    }

    rules = {
      articleId: [{ required: true, message: '请选择项目', trigger: 'change' }],
    }

    /**
     * 显示
     */
    private show(model: AccountModel){
      this.accountModel = model
      this.dialogVisible = true;
      this.loadAllArticle()
      this.$nextTick(() => {
        (this.$refs.form as Form).resetFields();
      })
    }

    /**
     * 加载所有项目
     */
    loadAllArticle() {
      this.articleListLoading = true
      ArticleModel.loadAllModels<ArticleModel>().then((dataArr: Array<ArticleModel>) => {
        // 获取所有已经存在的ID
        const currentIds = this.accountModel.projects.map((item: ArticleModel) => item._id)
        this.articleList = dataArr.filter((item: ArticleModel) => {
          return !currentIds.includes(item._id)
        })
      }).finally(() => {
        this.articleListLoading = false
      })
    }

    private okClick() {
      (this.$refs.form as Form).validate((valid) => {
        if (valid) {
          this.loading = true
          this.accountModel.addProject(this.form.articleId).then(() => {
            WPopView.msgSuccess('添加成功')
            this.dialogVisible = false
            this.$emit('reload')
          }).finally(() => {
            this.loading = false
          })
        } else {
          return false;
        }
      });
    }
  }

</script>

<style scoped>

</style>
